#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QFileDialog>
#include<QMessageBox>
#include<QStringList>
#include<QSqlRecord>
#include<QByteArray>
#include<QFile>
#include<QPixmap>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setCentralWidget(ui->splitter);
    // 设置tableView的属性
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setAlternatingRowColors(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::OpenTable()
{
    // 打开数据表
    m_psqlTableModel = new QSqlTableModel(this,m_dataBase);  // 数据表
    m_psqlTableModel->setTable("employee"); // 设置数据表
    m_psqlTableModel->setSort(m_psqlTableModel->fieldIndex("EmpNo"),Qt::AscendingOrder);
    // 设置编辑策略
    m_psqlTableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    if(!m_psqlTableModel->select())
    {
        QMessageBox::information(this,"错误","打开数据表错误,错误信息\n" +
                                                   m_psqlTableModel->lastError().text(), QMessageBox::Ok,QMessageBox::NoButton);
        return;
    }

    // 设置字段显示
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("EmpNo"),Qt::Horizontal,"工号");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Name"),Qt::Horizontal,"姓名");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Gender"),Qt::Horizontal,"性别");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Height"),Qt::Horizontal,"身高");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Birthday"),Qt::Horizontal,"出生日期");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Mobile"),Qt::Horizontal,"手机");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Province"),Qt::Horizontal,"省份");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("City"),Qt::Horizontal,"城市");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Department"),Qt::Horizontal,"部门");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Education"),Qt::Horizontal,"学历");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Salary"),Qt::Horizontal,"工资");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Memo"),Qt::Horizontal,"备注");
    m_psqlTableModel->setHeaderData(m_psqlTableModel->fieldIndex("Photo"),Qt::Horizontal,"照片");
    // 选择模型
    m_pSelection = new QItemSelectionModel(m_psqlTableModel);
    connect(m_pSelection,SIGNAL(currentChanged(QModelIndex,QModelIndex)),this,SLOT(On_currentChanged(QModelIndex,QModelIndex)));
    connect(m_pSelection,SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),this,SLOT(On_currentRowChanged(QModelIndex,QModelIndex)));
    // 设置数据模型
    ui->tableView->setModel(m_psqlTableModel);
    // 设置选择模型
    ui->tableView->setSelectionModel(m_pSelection);
    ui->tableView->setColumnHidden(m_psqlTableModel->fieldIndex("Momo"),true);
    ui->tableView->setColumnHidden(m_psqlTableModel->fieldIndex("Thoto"),true);
    // tablView上为性别和部门两个字段设置自定义代理组件
    QStringList strList;
    strList<<"男"<<"女";
    bool bIsEditable = false;
    m_delegateSex.setItems(strList,bIsEditable);
    ui->tableView->setItemDelegateForColumn(m_psqlTableModel->fieldIndex("Gender"),&m_delegateSex);

    strList.clear();
    strList << "销售部"<< "技术部"<< "生产部"<< "行政部";
    bIsEditable = true;
    m_delegateDepart.setItems(strList,bIsEditable);
    ui->tableView->setItemDelegateForColumn(m_psqlTableModel->fieldIndex("Department"),&m_delegateDepart);

    // 创建界面组件与数据模型字段之间的映射
    m_pdataMapper = new QDataWidgetMapper();
    // 设置数据模型
    m_pdataMapper->setModel(m_psqlTableModel);
    // 界面组件与具体字段之间的联系
    m_pdataMapper->addMapping(ui->spinBox,m_psqlTableModel->fieldIndex("EmpNo"));
    m_pdataMapper->addMapping(ui->lineEdit,m_psqlTableModel->fieldIndex("Name"));
    m_pdataMapper->addMapping(ui->comboBox_6,m_psqlTableModel->fieldIndex("Gender"));
    m_pdataMapper->addMapping(ui->spinBox_2,m_psqlTableModel->fieldIndex("Height"));
    m_pdataMapper->addMapping(ui->dateEdit,m_psqlTableModel->fieldIndex("Birthday"));
    m_pdataMapper->addMapping(ui->lineEdit_2,m_psqlTableModel->fieldIndex("Mobile"));
    m_pdataMapper->addMapping(ui->comboBox_3,m_psqlTableModel->fieldIndex("Province"));
    m_pdataMapper->addMapping(ui->lineEdit_3,m_psqlTableModel->fieldIndex("City"));
    m_pdataMapper->addMapping(ui->spinBox_3,m_psqlTableModel->fieldIndex("Department"));
    m_pdataMapper->addMapping(ui->comboBox_2,m_psqlTableModel->fieldIndex("Education"));
    m_pdataMapper->addMapping(ui->comboBox_4,m_psqlTableModel->fieldIndex("Salary"));
    m_pdataMapper->addMapping(ui->plainTextEdit,m_psqlTableModel->fieldIndex("Memo"));
    // 移动到首记录
    m_pdataMapper->toFirst();
    // 获取字段名称列表
    getFieldNames();
    // 更新actions和界面组件的使能状态
    ui->actOpenDB->setEnabled(false);
    ui->actRecAppend->setEnabled(true);
    ui->actRecInsert->setEnabled(true);
    ui->actRecDelete->setEnabled(true);
    ui->actScan->setEnabled(true);
    ui->groupBox->setEnabled(true);
    ui->groupBox_2->setEnabled(true);

}

void MainWindow::getFieldNames()
{
    // 获取所有字段名称
    QSqlRecord record = m_psqlTableModel->record(); // 获取空记录,只有字段名
    for(int i=0;i<record.count();i++)
    {
        ui->cbSort->addItem(record.fieldName(i));
    }
}

void MainWindow::on_actOpenDB_triggered()
{
    // 打开数据库
    QString strFileName = QFileDialog::getOpenFileName(this,"选择数据库文件","","SQLite 数据库(*.db *.db3)");
    if(strFileName.isEmpty())
        return;
    m_dataBase = QSqlDatabase::addDatabase("QSQLITE");
    m_dataBase.setDatabaseName(strFileName);
    if(!m_dataBase.open())
    {
        QMessageBox::warning(this,"错误","打开数据库失败",QMessageBox::Ok,QMessageBox::NoButton);
        return;
    }
    OpenTable();
}


void MainWindow::on_actQuit_triggered()
{

}


void MainWindow::on_actRecAppend_triggered()
{
    // 添加记录
    // 数据模型的的插入操作要怎么做？一问三不知,说明理解不够深入。
    // 先插入一行,然后才是添加数据
    m_psqlTableModel->insertRow(m_psqlTableModel->rowCount(),QModelIndex());
    QModelIndex curIndex = m_psqlTableModel->index(m_psqlTableModel->rowCount()-1,1);
    m_pSelection->clearSelection();
    m_pSelection->setCurrentIndex(curIndex,QItemSelectionModel::Select);
    int nCur = curIndex.row();
    m_psqlTableModel->setData(m_psqlTableModel->index(nCur,0),2000 + m_psqlTableModel->rowCount());
    m_psqlTableModel->setData(m_psqlTableModel->index(nCur,2),"男");
}


void MainWindow::on_actRecInsert_triggered()
{
    // 插入记录
    QModelIndex curIndex = ui->tableView->currentIndex();
    m_psqlTableModel->insertRow(curIndex.row(),QModelIndex());
    m_pSelection->clearSelection();
    m_pSelection->setCurrentIndex(curIndex,QItemSelectionModel::Select);
}


void MainWindow::on_actSubmit_triggered()
{
    // 保存修改
    bool bRes = m_psqlTableModel->submitAll();
    if(!bRes)
    {
        QMessageBox::information(this,"提示","数据保存错误,错误信息\n" + m_psqlTableModel->lastError().text());
    }
    else
    {
        ui->actSubmit->setEnabled(false);
        ui->actRevert->setEnabled(false);
    }
}


void MainWindow::on_actRevert_triggered()
{
    // 取消修改
    m_psqlTableModel->revertAll();
    ui->actSubmit->setEnabled(true);
    ui->actRevert->setEnabled(true);
}


void MainWindow::on_actRecDelete_triggered()
{
    // 删除记录
    QModelIndex curIndex = m_pSelection->currentIndex();
    m_psqlTableModel->revertRow(curIndex.row());
}


void MainWindow::on_actPhoto_triggered()
{
    QString strFile = QFileDialog::getOpenFileName(this,"选择图片","","照片(*.jpg)");
    if(strFile.isEmpty())
        return;

    QFile* pFile = new QFile(strFile);
    pFile->open(QIODevice::ReadOnly);
    QByteArray data = pFile->readAll();
    pFile->close();
    // 获取当前记录
    int nCurNo = m_pSelection->currentIndex().row();
    QSqlRecord curRec = m_psqlTableModel->record(nCurNo);
    // 设置字段数据
    curRec.setValue("Photo",data);
    m_psqlTableModel->setRecord(nCurNo,curRec);

    QPixmap pixmap;
    pixmap.load(strFile);
    ui->label_15->setPixmap(pixmap.scaledToWidth(ui->label_15->width()));

}


void MainWindow::on_actPotoClear_triggered()
{
    int nCurNo = m_pSelection->currentIndex().row();
    QSqlRecord curRec = m_psqlTableModel->record(nCurNo);
    // 设置字段数据
    curRec.setValue("Photo",NULL);
    m_psqlTableModel->setRecord(nCurNo,curRec);
    ui->label_15->clear();
}


void MainWindow::on_actScan_triggered()
{
    int nRowCount = m_psqlTableModel->rowCount();
    if(nRowCount == 0)
        return;

    for(int i=0;i< nRowCount;i++)
    {
        QSqlRecord actSal = m_psqlTableModel->record(i);
        float fsalary = actSal.value("Salary").toFloat();
        fsalary = fsalary * 1.1;
        m_psqlTableModel->setRecord(i,actSal);
    }
    m_psqlTableModel->submitAll();
    QMessageBox::information(NULL,"消息","涨工资计算完毕");
}

void MainWindow::On_currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    // 更新actSubmit和actRevert
    Q_UNUSED(current);
    Q_UNUSED(previous);
    ui->actSubmit->setEnabled(m_psqlTableModel->isDirty());
    ui->actRevert->setEnabled(m_psqlTableModel->isDirty());
}

void MainWindow::On_currentRowChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous);
    // 行切换时的状态控制
    ui->actRecDelete->setEnabled(current.isValid());
    ui->actPhoto->setEnabled(current.isValid());
    ui->actPotoClear->setEnabled(current.isValid());
    if(!current.isValid())
    {
        ui->label_15->clear(); // 清除图片显示
        return;
    }
    m_pdataMapper->setCurrentIndex(current.row()); // 更新数据映射的行号
    int ncurRecNo = current.row();// 获取行号
    QSqlRecord record = m_psqlTableModel->record(ncurRecNo); // 获取当前记录
    if(record.isNull("Photo"))
    {
        ui->label_15->clear(); // 清除图片显示
    }
    else
    {
        QByteArray data = record.value("Photo").toByteArray();
        QPixmap pic;
        pic.loadFromData(data);
        ui->label_15->setPixmap(pic.scaledToWidth(ui->label_15->size().width()));
    }
}

void MainWindow::on_radioBtnAscend_clicked()
{
    m_psqlTableModel->setSort(ui->cbSort->currentIndex(),Qt::AscendingOrder);
    m_psqlTableModel->select();
}


void MainWindow::on_radioBtnDesend_clicked()
{
    m_psqlTableModel->setSort(ui->cbSort->currentIndex(),Qt::DescendingOrder);
    m_psqlTableModel->select();
}


void MainWindow::on_cbSort_currentIndexChanged(int index)
{
    if(ui->radioBtnAscend->isChecked())
    {
        m_psqlTableModel->setSort(index,Qt::AscendingOrder);
    }
    else
    {
        m_psqlTableModel->setSort(index,Qt::DescendingOrder);
    }
    m_psqlTableModel->select();
}


void MainWindow::on_radioButton_4_clicked()
{
    m_psqlTableModel->setFilter("Gender = '男'");
}


void MainWindow::on_radioButton_3_clicked()
{
    m_psqlTableModel->setFilter("Gender = '女'");
}


void MainWindow::on_radioButton_5_clicked()
{
    m_psqlTableModel->setFilter("");
}

